package org.itboys.mobile.service.mongo.mobile;


import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.image.ImageUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.framework.resource.ResourceHolder;

import org.itboys.kitchen.entity.mysql.income.KitchenIncome;
import org.itboys.kitchen.entity.mysql.income.KitchenIncomeRecord;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.score.SundayScoreMapper;
import org.itboys.mobile.dto.SundayMemberDto;
import org.itboys.mobile.dto.score.SundayMemberFinanceDto;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.score.SundayScore;
import org.itboys.mobile.entity.mysql.score.SundayScoreConfig;
import org.itboys.mobile.entity.pos.member.PosMember;
import org.itboys.mobile.service.mysql.mobile.income.KitchenMobileIncomeService;
import org.itboys.mobile.service.mysql.mobile.score.SundayMobileScoreService;
import org.itboys.mobile.service.mysql.web.promotion.SundayPromotionService;
import org.itboys.mobile.service.mysql.web.score.SundayScoreConfigService;
import org.itboys.mobile.service.pos.PosMemberService;
import org.itboys.mobile.util.NameUtil;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.Sun;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_用户_service
 */
@Service
public class SundayMobileMemberService extends BaseMongoService<SundayMember> {

    @Autowired
    private SundayMobileCodeService codeService;
    @Autowired
    private SundayMobileAddressService addressService;
    @Autowired
    private SundayMobileCidService cidService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private SundayPromotionService promotionService;
    @Autowired
    private PosMemberService posMemberService;
    @Autowired
    private SundayMobileScoreService scoreService;

    @Autowired
    private KitchenMobileIncomeService incomeService;




    @Resource(name = "mobileDs")
    private MongoDataSource kitchenDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return kitchenDataSource;
    }

    @Override
    protected Class<SundayMember> getEntityClass() {
        return SundayMember.class;
    }



    /**
     * 用户注册（手机号+密码）。逻辑自定义。
     * @param mobile
     * @param code
     * @param password
     * @param villageId 小区ID。项目的特殊属性
     * @return
     */
    public SundayMemberDto register(String mobile,String password, String code,Long villageId){
        //2017年6月20日，新增，验证签名
        Map<String, Object> param =new HashMap<String,Object>();


        //校验验证码。
     int check_code=codeService.checkCode(mobile,code, SundayCommonConstants.validate_code_type_register);
     if(check_code!=0){
         throw new ErrorException("验证码错误。");
     }
        //校验用户
      param.clear();
        param.put("isDeleted",0);
        //实际校验mobile字段
        param.put("mobile",mobile);
        List<SundayMember> oldMembers = super.list(param);
        if(ListUtil.isNotNull(oldMembers)){
            throw new ErrorException("此手机号已被注册。");
        }
        SundayMember member = new SundayMember();
        member.setIsDeleted(0);
        member.setStatus(0);
        member.setUserName(NumberUtil.generateNumber("APP"));
        member.setUserType(SundayCommonConstants.user_type_member);
        member.setMobile(mobile);
        member.setNickName(NameUtil.getRandomName());
        member.setImage(NameUtil.getRandomLogo());

        member.setPassword(Digests.md5(password));
        member.setParentId(0l);
        super.save(member);
        //初始化用户其他信息
        initOtherInfo(member,villageId);
        //返回用户信息
        SundayMemberDto memberDto=packageDtoSingle(member);
        //设置用户的token。暂时是用户的秘密
      //  memberDto.setToken(member.getPassword());
         return memberDto;
    }

    /**
     * 登陆。手机号和密码登录.
     *
     * @param mobile。。
     * @param password
     * @return
     */
    public SundayMemberDto login(String mobile, String password,Integer loginType){
        //2017年6月20日，新增，验证签名
        Map<String, Object> param =new HashMap<String,Object>();
        /*param.put("mobile",mobile);
        param.put("password",password);
        param.put("loginType",loginType);
        param.put("nonce", nonce);
        param.put("sign", sign);
        boolean signSer = MobileSignUtils.signCheck(param, sign);
        if(!signSer){
            logger.warn("签名校验失败");
            throw new ErrorException("签名校验失败");
        }*/
        //查找用户
        param.clear();
        param.put("isDeleted", 0);
        param.put("mobile", mobile);
        param.put("password", Digests.md5(password));
        if(loginType==1){
            param.put("userType", SundayCommonConstants.user_type_member);
        }
        if(loginType==2){
            List<Integer> userTypes = new ArrayList<Integer>();
            userTypes.add(SundayCommonConstants.user_type_shop);
            userTypes.add(SundayCommonConstants.user_type_customer);
            param.put("userType in", userTypes);
        }
        List<SundayMember> members = super.list(param);
        if (ListUtil.isNull(members)) {
            throw new ErrorException("账户或密码错误");

        }
        SundayMember member=members.get(0);
        if (member.getStatus()!=0) {
            throw new ErrorException("账户被冻结");

        }
        SundayMemberDto memberDto=packageDtoSingle(member);
        //设置用户的token。暂时是用户的秘密
        //memberDto.setToken(member.getPassword());

        return memberDto;
    }




    /**
     * 第三方登陆,第一步。只传入第三方信息。农厨第三方登陆需要绑定手机号和小区
     * @param thirdType
     * @param unionId
     * @return
     */
    public SundayMemberDto loginWithThirdOne(Integer thirdType,String unionId){
        //2017年6月20日，新增，验证签名
        Map<String, Object> param =new HashMap<String,Object>();
       /* param.put("thirdType",thirdType);
        param.put("unionId",unionId);
        param.put("nonce", nonce);
        param.put("sign", sign);
        boolean signSer = MobileSignUtils.signCheck(param, sign);
        if(!signSer){
            logger.warn("签名校验失败");
            throw new ErrorException("签名校验失败");
        }*/

        //校验用户
      param.clear();
        param.put("isDeleted",0);
        //校验第三方unionId
        if(thirdType==SundayCommonConstants.third_type_weixin){
            param.put("weixinUnionId",unionId);
        }else if(thirdType==SundayCommonConstants.third_type_qq){
            param.put("qqUnionId",unionId);
        }else if(thirdType==SundayCommonConstants.third_type_weibo){
            param.put("weiboUnionId",unionId);
        }else{
             throw new ErrorException("登陆类型错误");
        }
        List<SundayMember> oldMembers = super.list(param);
        if(ListUtil.isNull(oldMembers)){

            //如果为空，调用第三方登陆，第二步
            return null;
        }



        return packageDtoSingle(oldMembers.get(0));
    }
    /**
     * 第三方登陆,第二步。传入第三方信息和手机号。农厨第三方登陆需要绑定手机号和小区
     * @param thirdType
     * @param unionId
     * @param mobile
     * @return
     */
    public SundayMemberDto loginWithThirdTwo(Integer thirdType,String nickName,String image, String unionId, String mobile,String code) {

        //检验验证码
        int reulct_code =codeService.checkCode(mobile,code,SundayCommonConstants.validate_code_type_login);
        if(reulct_code!=0){
            throw new ErrorException("验证码错误");
        }
        //校验用户
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",0);
        param.put("mobile",mobile);
        //校验第三方unionId
        /*if(thirdType==SundayCommonConstants.third_type_weixin){
            param.put("weixinUnionId",unionId);
        }else if(thirdType==SundayCommonConstants.third_type_qq){
            param.put("qqUnionId",unionId);
        }else if(thirdType==SundayCommonConstants.third_type_weibo){
            param.put("weiboUnionId",unionId);
        }else{
            throw new ErrorException("登陆类型错误");
        }*/
        List<SundayMember> oldMembers = super.list(param);
        if(ListUtil.isNull(oldMembers)){
            //如果为空，调用第三方登陆，第三步
            return null;
        }
        //获取第三方信息。头像，昵称，unionId。替换用户的信息
        SundayMember member = oldMembers.get(0);
        member.setNickName(nickName);
        //保存unionId
        if(thirdType==SundayCommonConstants.third_type_weixin){
            member.setWeixinUnionId(unionId);
        }else if(thirdType==SundayCommonConstants.third_type_qq){
            member.setQqUnionId(unionId);
        }else if(thirdType==SundayCommonConstants.third_type_weibo){
            member.setWeiboUnionId(unionId);
        }
        //获取第三方头像。半链接
           String random=String.valueOf(new Date().getTime());
        //如果当前项目的上传文件目录下没有logo文件夹，请自行创建。此文件夹存放的是默认的头像和第三方登陆用户头像
        String savePath = resourceHolder.getStringValue("fileUploadPath")+"/logo/"+random+".jpg";
       ImageUtils.buildImg(savePath,image);
       member.setImage("/logo/"+random+".jpg");
        super.updateExceptEmpty(member.getId(),member);
        SundayMemberDto memberDto=packageDtoSingle(member);

        return memberDto;
    }

    /**
     * 第三方登陆,第三步。传入第三方信息，手机号，密码，小区信息。农厨第三方登陆需要绑定手机号和小区
     * @param thirdType
     * @param nickName
     * @param image
     * @param unionId
     * @param mobile
     * @param code
     * @param password
     * @param villageId
     * @return
     */
    public SundayMemberDto loginWithThirdThree(Integer thirdType,String nickName,String image, String unionId, String mobile,String code,String password,Long villageId) {
        //校验用户
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",0);
        param.put("mobile",mobile);
        //校验第三方unionId
        if(thirdType==SundayCommonConstants.third_type_weixin){
            param.put("weixinUnionId",unionId);
        }else if(thirdType==SundayCommonConstants.third_type_qq){
            param.put("qqUnionId",unionId);
        }else if(thirdType==SundayCommonConstants.third_type_weibo){
            param.put("weiboUnionId",unionId);
        }else{
            throw new ErrorException("登陆类型错误");
        }
        List<SundayMember> oldMembers = super.list(param);
        SundayMember member = new SundayMember();
        //创建用户
        if(ListUtil.isNull(oldMembers)){
            member.setIsDeleted(0);
            member.setStatus(0);
            member.setUserName(NumberUtil.generateNumber("APP"));
            member.setUserType(SundayCommonConstants.user_type_member);
            member.setMobile(mobile);
            member.setNickName(nickName);
            member.setParentId(0l);
            //获取第三方头像。半链接
            String random=String.valueOf(new Date().getTime());
            //如果当前项目的上传文件目录下没有logo文件夹，请自行创建。此文件夹存放的是默认的头像和第三方登陆用户头像
            String savePath = resourceHolder.getStringValue("fileUploadPath")+"/logo/"+random+".jpg";
            ImageUtils.buildImg(savePath,image);
            member.setImage("/logo/"+random+".jpg");
            //保存unionId
            if(thirdType==SundayCommonConstants.third_type_weixin){
                member.setWeixinUnionId(unionId);
            }else if(thirdType==SundayCommonConstants.third_type_qq){
                member.setQqUnionId(unionId);
            }else if(thirdType==SundayCommonConstants.third_type_weibo){
                member.setWeiboUnionId(unionId);
            }
            member.setPassword(Digests.md5(password));
            super.save(member);
            //初始化用户其他信息
            initOtherInfo(member,villageId);
        //返回用户信息。此步骤是避免接口端误操作第二步。
        }else{
            member=oldMembers.get(0);
        }
        SundayMemberDto memberDto=packageDtoSingle(member);
        //设置用户的token。暂时是用户的秘密
       // memberDto.setToken(member.getPassword());
        return memberDto;
    }

    /**
     * 退出登录。删除CID
     * @param memberId
     */
    public void logout(long memberId){
        cidService.clear(memberId);
    }
    /**
     * 修改个人信息
     * @param memberId
     * @param  nickName
     * @param mobileName
     * @param address
     * @param email
     * @param image
     * @param idCard
     * @param desc
     */
    public SundayMemberDto update(Long memberId,String nickName,String mobileName,String address,String email,
                                  String image,String idCard,String desc){

        SundayMember member = new SundayMember();
        member.setId(memberId);
        member.setNickName(nickName);
        member.setMobileName(mobileName);
        member.setAddress(address);
        member.setEmail(email);
        member.setImage(image);
        member.setIdCard(idCard);
        member.setDesc(desc);
        super.updateExceptEmpty(memberId,member);
        return packageDtoSingle(super.getById(memberId));
    }

    /**
     * 获取用户详情
     * @param memberId
     * @return
     */
    public SundayMemberDto findOne(Long memberId){
        return packageDtoSingle(super.getById(memberId));
    }

    /**
     * 修改密码。使用旧密码
     * @param memberId
     * @param oldPassword
     * @param newPassword
     */
    public void updatePassword(Long memberId,String oldPassword,String newPassword){

       SundayMember member = super.getById(memberId);
        if (!Digests.md5(oldPassword).equalsIgnoreCase(member.getPassword())) {
            throw new ErrorException("旧密码错误");
        }
        super.update(memberId,"password",newPassword);
    }


    /**
     * 修改密码。使用验证码
     * @param memberId
     * @param mobile
     * @param newPassword
     * @param code
     */
    public void updatePasswordWithCode(Long memberId,String mobile,String newPassword,String code){
        //2017年6月20日，新增，验证签名
       Map<String, Object> param =new HashMap<String,Object>();
      /*   param.put("mobile",mobile);
        param.put("newPassword",newPassword);
        param.put("code",code);
        param.put("nonce", nonce);
        param.put("sign", sign);
        boolean signSer = MobileSignUtils.signCheck(param, sign);
        if(!signSer){
            logger.warn("签名校验失败");
            throw new ErrorException("签名校验失败");
        }*/
        //校验验证码。
        int check_code=codeService.checkCode(mobile,code, SundayCommonConstants.validate_code_type_update_password);
        if(check_code!=0){
            throw new ErrorException("验证码错误。");
        }
        param.clear();
        param.put("isDeleted", 0);
        param.put("mobile", mobile);
        List<SundayMember> members = super.list(param);
        if(ListUtil.isNotNull(members)){
            SundayMember member = members.get(0);
            super.update(member.getId(),"password",Digests.md5(newPassword));
        }
    }
    /**
     * 忘记密码。
     * @param mobile
     * @param newPassword
     * @param code
     */
    public void forgetPassword(String mobile,String newPassword,String code){
       //2017年6月20日，新增，验证签名
        Map<String, Object> param =new HashMap<String,Object>();
       /*  param.put("mobile",mobile);
        param.put("newPassword",newPassword);
        param.put("code",code);
        param.put("nonce", nonce);
        param.put("sign", sign);
        boolean signSer = MobileSignUtils.signCheck(param, sign);
        if(!signSer){
            logger.warn("签名校验失败");
            throw new ErrorException("签名校验失败");
        }*/
        //校验验证码。
        int check_code=codeService.checkCode(mobile,code, SundayCommonConstants.validate_code_type_forget_password);
        if(check_code!=0){
            throw new ErrorException("验证码错误。");
        }
      param.clear();
        param.put("isDeleted", 0);
        param.put("mobile", mobile);
        List<SundayMember> members = super.list(param);
        if(ListUtil.isNotNull(members)){
            SundayMember member = members.get(0);
            super.update(member.getId(),"password",Digests.md5(newPassword));
        }
    }

    /**
     * 设置支付宝密码
     * @param memberId
     * @param payPassword
     * @param code
     */
    public void setPayPassword(Long memberId,String payPassword,String code){
    /*    Map<String, Object> param =new HashMap<String,Object>();
        param.put("payPassword",payPassword);
        param.put("code",code);
        param.put("nonce", nonce);
        param.put("sign", sign);
        boolean signSer = MobileSignUtils.signCheck(param, sign);
        if(!signSer){
            logger.warn("签名校验失败");
            throw new ErrorException("签名校验失败");
        }*/
        SundayMember member =super.getById(memberId);
        logger.info("member_id="+member.getId()+",member_mobile="+member.getMobile());
        //校验验证码。
        int check_code=codeService.checkCode(member.getMobile(),code, SundayCommonConstants.validate_code_type_set_pay_password);
        if(check_code!=0){
            throw new ErrorException("验证码错误。");
        }
        super.update(member.getId(),"payPassword",Digests.md5(payPassword));
    }

    /**
     * 修改支付密码
     * @param memberId
     * @param newPayPassword
     * @param code
     */
    public void updatePayPassWord(Long memberId,String newPayPassword,String code){
        /*Map<String, Object> param =new HashMap<String,Object>();
        param.put("newPayPassword",newPayPassword);
        param.put("code",code);
        param.put("nonce", nonce);
        param.put("sign", sign);
        boolean signSer = MobileSignUtils.signCheck(param, sign);
        if(!signSer){
            logger.warn("签名校验失败");
            throw new ErrorException("签名校验失败");
        }*/
        SundayMember member =super.getById(memberId);
        //校验验证码。
        int check_code=codeService.checkCode(member.getMobile(),code, SundayCommonConstants.validate_code_type_update_pay_password);
        if(check_code!=0){
            throw new ErrorException("验证码错误。");
        }
        super.update(member.getId(),"payPassword",Digests.md5(newPayPassword));
    }

    /**
     * 校验支付密码
     * @param memberId
     * @param payPassword
     */
    public void checkPayPassWord(Long memberId,String payPassword){

        SundayMember member =super.getById(memberId);
        if(!StringUtils.isNotEmpty(member.getPayPassword())){
            throw new ErrorException("未设置支付密码");
        }
        if(!member.getPayPassword().equalsIgnoreCase(Digests.md5(payPassword))){
            throw new ErrorException("支付密码错误");
        }
    }

    /**
     * 用户创建时，自动创建用户的其他信息
     */
    public void initOtherInfo(SundayMember member,Long villageId){
        //创建用户积分主表
        //创建用户余额主表
        //创建用户小区(即收货地址)
      addressService.saveAddress(0l,member.getId(),villageId,member.getNickName(),member.getMobile(),
              null,null,null,null,null,null,null);
      //赠送优惠券
        promotionService.sendCouponByRegister(member.getId());
    }
    /**
     * 组装用户DTO。逻辑可以自定义
     */
    public SundayMemberDto packageDtoSingle(SundayMember member) {
        SundayMemberDto memberDto =new SundayMemberDto(member.getId(),member.getCreateTime(), member.getCreateDate(),
                member.getUserName(), member.getNickName(), member.getMobile(), member.getMobileName(),
                member.getAddress(), member.getEmail(), member.getUserType(),resourceHolder.getStringValue("imgRoot")+member.getImage(), member.getIdCard(), member.getDesc(),
                member.getStatus(),null, null,member.getDiscount()==null?null:new BigDecimal(member.getMobile()).setScale(2,BigDecimal.ROUND_HALF_UP));


         memberDto.setShareUrl(resourceHolder.getStringValue("mobileRoot")+"/sunday/mobile/member/share?id="+member.getId());
        memberDto.setShareImage(memberDto.getImage());
        memberDto.setShareTitle("花果山果蔬 用户推广");
        memberDto.setShareDesc("我是："+memberDto.getNickName()+",我为【花果山果蔬】代言，快来加入吧");
        //设置用户的token。暂时是用户的秘密
        memberDto.setToken(member.getPassword());
        //判断用户是否设置支付密码
        memberDto.setIsPayPassword(StringUtils.isNoneEmpty(member.getPayPassword())?1:0);
        return  memberDto;
    }
    public List<SundayMemberDto>  packageDtoMuilt( List<SundayMember> members) {
        List<SundayMemberDto> dtos = new ArrayList<SundayMemberDto>();
        for(SundayMember member:members){
            dtos.add( packageDtoSingle(member));
        }
        return dtos;
    }
    /**
     * 查找门店的送货员
     * @param shopId
     * @return
     */
    public List<Map<String ,Object>> getDeliveryMan(Long shopId){
        Map<String,Object> param=new HashMap<String ,Object>();
        param.put("isDeleted",0);
        param.put("userType",SundayCommonConstants.user_type_shop);
        param.put("parentId",shopId);
        List<Map<String,Object>> result=new ArrayList<Map<String,Object>>();
        Map<String ,Object> map=new HashMap<String,Object>();
        List<SundayMember >members= super.list(param);
        if(ListUtil.isNotNull(members)){
            for(SundayMember member:members){
                map.put("id",member.getId());
                map.put("mobileName",member.getMobileName());
                map.put("mobile",member.getMobile());
                result.add(map);
            }
        }
        return result;
    }
    /**
     * ----------------会员卡相关------------------------
     */
    /**
     * 会员卡首页
     * @param memberId
     */
    public Map<String,Object> member_card_index(Long memberId){
        Map<String,Object> result = new HashMap<String,Object>();;
        SundayMember member = super.getById(memberId);
        if(StringUtils.isNotEmpty(member.getCardNo())){
            result.put("isCard",1);
            result.put("cardNo",member.getCardNo());
            result.put("cardType",member.getCartType());
            if(member.getCartType().equals("01")){
                result.put("discount","9.5折");
            }else if(member.getCartType().equals("02")){
                    result.put("discount","8.8折");
            }else{
                result.put("discount","无折扣");
            }
            SundayMemberFinanceDto memberFinanceDto=getMemberFinance(null,member);
            result.put("balance",memberFinanceDto.getBalance());
            result.put("score",memberFinanceDto.getScore());
        }else{
            result.put("isCard",0);
            result.put("memberId",memberId);
        }

        return result;
    }
    /**
     *会员卡_绑定
     */
    public void member_card_bind(Long memberId,String cardNo,String mobile,String code){
        //1，校验验证码
        codeService.checkCode(mobile,code,SundayCommonConstants.validate_code_type_sign_card);
        //2,校验用户是否绑定过会员
        SundayMember member = super.getById(memberId);
        if(StringUtils.isNotEmpty(member.getCardNo())){
            throw new ErrorException("您已经绑定过会员卡");
        }
        //2.1,校验此会员卡是否被绑定过
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",0);
        param.put("cardNo",cardNo);
        if(super.count(param)>0){
            throw new ErrorException("此会员已经被其他用户绑定！");
        }
        //3,从pos查询会员卡信息
        PosMember posMember=posMemberService.getPosMember(cardNo);
        //4,比对pos中会员卡信息是否和本次绑定信息一致
        if(!posMember.CardNO.trim().equalsIgnoreCase(cardNo)||
                !posMember.MobileNo.trim().equalsIgnoreCase(mobile)||
                !posMember.Status.trim().equalsIgnoreCase("1")){
            throw new ErrorException("会员卡信息有误，请联系发卡门店");
        }
        //5,写入会员卡信息
        member.setCardNo(cardNo);
        member.setCartType(posMember.CardType);
        super.updateExceptEmpty(memberId,member);
        //6，同步已经在线上积累的余额和积分
        SundayScore score=scoreService.findOne(memberId);
        if(score.getAbleScore().compareTo(new BigDecimal("0"))==1){
            posMemberService.changePosScore(cardNo, score.getAbleScore(),PosMemberService.score_transType_Reward, "Sign-"+mobile);
        }
        KitchenIncome income=incomeService.findOne(memberId);
        if(income.getAbleRevenue().compareTo(new BigDecimal("0"))==1){
            posMemberService.addPosBalance(cardNo,income.getAbleRevenue(),income.getAbleRevenue());
        }
    }
    /**
     * 会员卡_查询积分、余额、折扣_映射到用户dto中，积分和余额
     */
    public SundayMemberFinanceDto getMemberFinance(Long memberId, SundayMember member){
        BigDecimal score =new BigDecimal("0");//用户剩余积分。用户DTO中体现
        BigDecimal balance=new BigDecimal("0");//用户剩余额。用户DTO中体现
         BigDecimal discount=new BigDecimal("1");//用户折扣。小于1的小数
         String status="";//会员卡状态。0未发卡,1已发卡,8挂失,9作废
      if(member==null){
          member=super.getById(memberId);
      }
        //注册会员
        if(member.getUserType()==SundayCommonConstants.user_type_member){
            //绑定了会员卡
            if(StringUtils.isNotEmpty(member.getCardNo())){
               PosMember posMember= posMemberService.getPosMember(member.getCardNo());
               score=posMember.Integral;
               balance=posMember.ResidualAmt;
               status=posMember.Status;
               //绿卡
               if(posMember.CardType.equalsIgnoreCase("01")){
                   discount=new BigDecimal("0.95");
                //黑卡
               }else if(posMember.CardType.equalsIgnoreCase("02")){
                    discount=new BigDecimal("0.88");
               }
            //未绑定会员卡
            }else{
                score = scoreService.findOne(memberId).getAbleScore();
                balance=incomeService.findOne(memberId).getAbleRevenue();
                //discount=
            }
            //大客户
        }else if(member.getUserType()==SundayCommonConstants.user_type_customer){
            discount=new BigDecimal(member.getDiscount().doubleValue()/100).setScale(2,BigDecimal.ROUND_HALF_UP);

            //门店
        }else{

        }
        score.setScale(2,BigDecimal.ROUND_HALF_UP);
        balance.setScale(2,BigDecimal.ROUND_HALF_UP);
        discount.setScale(2,BigDecimal.ROUND_HALF_UP);
        return new SundayMemberFinanceDto(score,  balance,  discount,  status);
    }
    /**
     * ----------------------------------变更积分------------------------
     */

    /**
     *
     * @param orderNo
     * @param thisScore
     * @param type
     * @param memberId
     */
    public void changeScore(String orderNo,BigDecimal thisScore, Integer type, Long memberId){
        SundayMember member =super.getById(memberId);
        if(member.getUserType()==SundayCommonConstants.user_type_member){
            //生成本地积分记录
                scoreService.generateRecord2(orderNo,thisScore,type,memberId);
            //绑定了会员卡。将积分数据传入pos
            if(StringUtils.isNotEmpty(member.getCardNo())){
               BigDecimal RealIntegral = thisScore.compareTo(new BigDecimal("0"))==1?thisScore:thisScore.multiply(new BigDecimal("-1"));

                String TransType =SundayCommonConstants.score_transType_offset;
                if(type==SundayCommonConstants.SCORE_TYPE_REWARD||
                        type==SundayCommonConstants.SCORE_TYPE_SIGN||
                        type==SundayCommonConstants.SCORE_TYPE_RETURN){
                    TransType= SundayCommonConstants.score_transType_Reward;
                }else{
                    TransType =SundayCommonConstants.score_transType_offset;
                }
                posMemberService.changePosScore(member.getCardNo(), RealIntegral,TransType, orderNo);

            }

        }

    }
    /**
     *
     */
    /**
     * 变更余额
     * @param memberId
     * @param type
     * @param orderNo
     * @param payAmount
     * @param incomeRecords 充值成功后相关
     * @param out_trade_no 充值成功后相关
     */
    public void changeBalance(Long memberId,
                              Integer type,
                              String orderNo,
                              BigDecimal payAmount,
                              List<KitchenIncomeRecord> incomeRecords,
                              String out_trade_no){
        SundayMember member =super.getById(memberId);
        if(member.getUserType()==SundayCommonConstants.user_type_member){
            //生成本地充值记录

                incomeService.generateRecord2(memberId,
                        type,
                        orderNo,
                        payAmount,
                        incomeRecords,
                        out_trade_no);



            //绑定了会员卡。将余额数据传入pos
            if(StringUtils.isNotEmpty(member.getCardNo())){
                //余额变更类型
                if(type==SundayCommonConstants.income_record_type_charge||
                        type== SundayCommonConstants.income_record_type_free||
                        type== SundayCommonConstants.income_record_type_cancel){
                    posMemberService.addPosBalance(member.getCardNo(),payAmount,payAmount);
                }else if(type==SundayCommonConstants.income_record_type_consume){
                    posMemberService.deductionPosBalance(member.getCardNo(),payAmount,orderNo);
                }

            }

        }

    }

}
